package data.nanjing.expo.services;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import data.nanjing.expo.common.ExpoConstants;
import data.nanjing.expo.models.domain.FileManage;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zjp on 2018/6/25.
 * QQ：34948062
 * github: https://www.github.com/zjp1029
 * web： http://www.zjp1029.cn
 */

@Service
public class FileUtilService {

    @Value("${qiniu.access.key}")
    private String accessKey;

    @Value("${qiniu.secret.key}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qinniu.download.address}")
    private String downloadAddress;

    /**
     * 统一上传文件接口
     * @param
     * @return
     */
    public Map<String, String> uploadFile(MultipartFile file) throws IOException {
        Map<String, String> map = new HashMap<>();
        //基本配置
        Configuration configuration = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(configuration);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        //获得文件流
        InputStream inputStream = file.getInputStream();
        try {
            Response response = uploadManager.put(inputStream, null, upToken, null, null);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            map.put("filename", file.getOriginalFilename());
            map.put("key", putRet.key);
            map.put("hash", putRet.hash);
            map.put("fileType", getFileType(file.getOriginalFilename()));
            map.put("finalPath", String.format("%s/%s", downloadAddress, putRet.key));
            return map;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //获取文件的真实地址
    public String getRealFileAddress(String key) throws UnsupportedEncodingException {
        String encodedKey = URLEncoder.encode(key, "utf-8");
        String finalUrl = String.format("%s/%s", downloadAddress, encodedKey);
        return finalUrl;
    }


    //获取文件的类型
    private String getFileType(String fileName) {
        String lowerFileName = fileName.toLowerCase();
        if (lowerFileName.endsWith("jpg") || lowerFileName.endsWith("png") || lowerFileName.endsWith("jpeg")
                || lowerFileName.endsWith("gif")) {
            return ExpoConstants.TYPE_IMAGE; //图片
        }else if (lowerFileName.endsWith("mp3") || lowerFileName.endsWith("wav") || lowerFileName.endsWith("wma")
                || lowerFileName.endsWith("midi")) {
            return ExpoConstants.TYPE_AUDIO;     //音频
        }else if (lowerFileName.endsWith("mp4") || lowerFileName.endsWith("avi") || lowerFileName.endsWith("mov")) {
            return ExpoConstants.TYPE_VIDEO;     //视频
        }else if (lowerFileName.endsWith("txt") || lowerFileName.endsWith("doc") || lowerFileName.endsWith("docx")
                || lowerFileName.endsWith("ppt") || lowerFileName.endsWith("pptx") || lowerFileName.endsWith("xls")
                || lowerFileName.endsWith("xlsx") || lowerFileName.endsWith("pdf")) {
            return ExpoConstants.TYPE_DOCUMENT;  //文档
        }else {
            return ExpoConstants.TYPE_OTHER;     //其他
        }
    }


    /**
     * 下载单个文件
     * @param fileManage
     * @param request
     * @param response
     */
    public void downloadFile(FileManage fileManage, HttpServletRequest request, HttpServletResponse response) {
        try {
            String key = fileManage.getFileKey();
            String fileName = fileManage.getFileName();

            String encodedKey = URLEncoder.encode(key, "utf-8");
            String finalUrl = String.format("%s/%s", downloadAddress, encodedKey);
            //下载开始
            URL url = new URL(finalUrl);
            URLConnection connection = url.openConnection();
            BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename="+processFileName(request.getHeader("USER-AGENT"), fileName));
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //读取字节流写入文件
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer, 0, 1024)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 下载压缩文件
     * @param request
     * @param response
     * @param fileManages
     * @param zipName
     */
    public void downloadZipFile(HttpServletRequest request, HttpServletResponse response,
                                List<FileManage> fileManages, String zipName) throws IOException {
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
        zipOutputStream.setMethod(ZipOutputStream.DEFLATED);    //设置压缩方法:边压缩边下载
        DataOutputStream dataOutputStream = null;
        try {
            //1.设置响应头
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            //文件名
            response.setHeader("Content-Disposition", "attachment;fileName="+processFileName(request.getHeader("USER-AGENT"), zipName));

            //2.设置压缩流，直接写入response，实现便压缩边下载
            for (int i = 0; i < fileManages.size(); i++) {
                //3.添加ZipEntity(要压缩的文件)，写入文件流
                zipOutputStream.putNextEntry(new ZipEntry((i + 1) + fileManages.get(i).getFileName()));
                dataOutputStream = new DataOutputStream(zipOutputStream);
                String encodedKey = URLEncoder.encode(fileManages.get(i).getFileKey(), "utf-8");
                String finalUrl = String.format("%s/%s", downloadAddress, encodedKey);
                URL url = new URL(finalUrl);
                URLConnection connection = url.openConnection();
                BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(b)) != -1) {
                    dataOutputStream.write(b, 0, len);
                }
                inputStream.close();
                zipOutputStream.closeEntry();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.flush();
                    dataOutputStream.close();
                }
                if (zipOutputStream != null){
                    zipOutputStream.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据不同内核的浏览器，对文件名格式转化
     * @param agent
     * @param name
     * @return
     */
    private String processFileName(String agent, String name) throws UnsupportedEncodingException {
        if (agent.contains("MSIE") || agent.contains("Trident")) {
            return URLEncoder.encode(name, "UTF-8");
        }else if (agent.contains("Mozilla")){
            return new String(name.getBytes("UTF-8"), "iso8859-1");
        }else {
            return name;
        }
    }

}
